package io.zt.dangyuan;

import android.CaptureActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.HttpException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.zt.dangyuan.object.UserModel;
import io.zt.dangyuan.util.Cons;

/**
 * Created by Administrator on 2015/7/6.
 */
public class MyAdminActivity extends BaseActivity {

    @InjectView(R.id.avart)
    CircleImageView avart;
    @InjectView(R.id.name)
    TextView name;
    @InjectView(R.id.et_send_title)
    TextView tv_pwd;
    @InjectView(R.id.et_send_content2)
    TextView tv_code;
    @InjectView(R.id.et_send_content)
    TextView tv_contact;
    @InjectView(R.id.btn_logout)
    TextView btnExit;
    @InjectView(R.id.et_send_personal)
    TextView tv_personal;
    @InjectView(R.id.saoyisao)
    ImageView imageView;
    @InjectView(R.id.come_back)
    ImageView imageView2;

    private AlertDialog.Builder builder;

    public static final int PHOTOZOOM = 0; // 相册/拍照
    public static final int PHOTOTAKE = 1; // 相册/拍照
    public static final int IMAGE_COMPLETE = 2; // 结果
    private String photoSavePath;//保存路径
    private String photoSaveName;//图pian名
    private String path;//图片全路径
    private int userid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        ButterKnife.inject(this);
        //始终保持竖屏
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //setTitleImg(R.drawable.title_wode);
        //toolbar.setNavigationIcon(R.drawable.icon_pre);
//        CircleImageView img = (CircleImageView) findViewById(R.id.id_circle_menu_center_img);
        avart.setBorderColor(Color.parseColor("#C63A45"));
        avart.setBorderWidth(4);
        final GlobalDataApplication app = (GlobalDataApplication) getApplication();
        userid = app.getUserModel().getUserid();
        loadHead(app);
//        BitmapUtils bitmapUtils = new BitmapUtils(this);
////        // 加载网络图片
//        bitmapUtils.display(avart,  Cons.BASE_URL+ app.getUserModel().getUserimg());

        name.setText(app.getUserModel().getRealname());

        tv_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MyAdminActivity.this, AddressListActivity.class).putExtra("groupid", ""));
            }
        });
        tv_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MyAdminActivity.this, ChangePassActivity.class));
            }
        });
        tv_personal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MyAdminActivity.this, PersonalActivity2.class));
            }
        });
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final GlobalDataApplication app = (GlobalDataApplication) getApplication();
                app.setUserModel(null);
                finish();
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                //intent.putExtra("textIndex", result);
                intent.setClass(MyAdminActivity.this, CaptureActivity.class);
                startActivity(intent);
                //showPopupWindow();
//               AddPopWindow addPopWindow = new AddPopWindow(BaseActivity.this);
//            addPopWindow.showPopupWindow(titleImg2);
            }

        });
        imageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               finish();
            }

        });


    }

    public void loadHead(GlobalDataApplication app) {
        if (app != null) {
            Glide.with(this).load(Cons.BASE_URL + app.getUserModel().getUserimg()).placeholder(R.drawable.ic_laucher).into(avart);
            Log.e("asd",Cons.BASE_URL + app.getUserModel().getUserimg());
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_read_love, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
public void onClick(){
    finish();
}

    /**
     * 头像的点击事件
     */
    public void change_head_click(View view) {
        File file = new File(Environment.getExternalStorageDirectory(), "ClipHeadPhoto/cache");
        if (!file.exists())
            file.mkdirs();
        photoSavePath = Environment.getExternalStorageDirectory() + "/ClipHeadPhoto/cache/";
        String[] items = new String[]{"拍照", "从手机中选择"};
        // 实例化对话框
        builder = new AlertDialog.Builder(this);
        // 设置对话框标题
        builder.setTitle("选择图片");
        //
        builder.setIcon(android.R.drawable.ic_menu_more);
        // 简单的列表项对话框
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int id) {
                switch (id) {
                    case 0:
                        doTakePhoto();
                        break;
                    case 1:
                        doSelectImageFromLoacal();
                        break;
                }
                // 关闭对话框
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.show();
    }


    /**
     * 拍照获取图片
     */
    public void doTakePhoto() {
        photoSaveName = String.valueOf(System.currentTimeMillis()) + ".png";
        Uri imageUri = null;
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        imageUri = Uri.fromFile(new File(photoSavePath, photoSaveName));
        openCameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, PHOTOTAKE);

    }

    /**
     * 从相册中选择
     */
    public void doSelectImageFromLoacal() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.putExtra("return-data", false);
        startActivityForResult(intent, PHOTOZOOM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        Uri uri = null;
        switch (requestCode) {
            case PHOTOZOOM://相册
                if (data == null) {
                    return;
                }
                uri = data.getData();
                String[] proj = {MediaStore.Images.Media.DATA};
//                Cursor cursor = managedQuery(uri, proj, null, null,null);
                Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();//定位在第一行
                path = cursor.getString(column_index);// 图片在的路径
                Intent intent3 = new Intent(this, ClipActivity.class);
                intent3.putExtra("path", path);
                startActivityForResult(intent3, IMAGE_COMPLETE);
                break;
            case PHOTOTAKE://拍照
                path = photoSavePath + photoSaveName;
                uri = Uri.fromFile(new File(path));
                Intent intent2 = new Intent(this, ClipActivity.class);
                intent2.putExtra("path", path);
                startActivityForResult(intent2, IMAGE_COMPLETE);
                break;
            case IMAGE_COMPLETE:
                final String temppath = data.getStringExtra("path");
                upload(path);
                break;
            default:
                break;
        }
    }

    /**
     * 上传头像
     *
     * @param path
     */
    private void upload(final String path) {
        String url = Cons.BASE_URL+"/tq/api/uploadUserImg.json";
        //携带的数据
        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put("userid", String.valueOf(userid));
        params.put("uploadFile", new File(path));
        WebUtils.sendPost(MyAdminActivity.this, url, params, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                String result = data;
                String uri = "";
                try {
                    JSONObject json = new JSONObject(result);
                    uri = json.getString("message");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                UserModel model = ((GlobalDataApplication) getApplication()).getUserModel();
                model.setUserimg(uri);
                ((GlobalDataApplication) getApplication()).setUserModel(model);
                avart.setImageBitmap(getLoacalBitmap(path));
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                Toast.makeText(MyAdminActivity.this, "上传失败" +msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

}
